package com.temi.iot.config.shiro;

import com.temi.iot.jwt.DefaultTokenService;
import com.temi.iot.jwt.JwtUtil;
import com.temi.iot.jwt.model.TokenValue;
import io.jsonwebtoken.Claims;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.web.subject.WebSubject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;


/**
 * 自定义身份认证
 * 基于HMAC（ 散列消息认证码）的控制域
 */

public class JWTShiroRealm extends AuthorizingRealm {
	private final Logger log = LoggerFactory.getLogger(JWTShiroRealm.class);

	@Autowired
    private JwtUtil jwtUtil;

    public JWTShiroRealm(){
        this.setCredentialsMatcher(new JWTCredentialsMatcher());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        JWTToken jwtToken = (JWTToken)authcToken;
        ServletRequest servletRequest = ((WebSubject) SecurityUtils.getSubject()).getServletRequest();
        HttpServletRequest request = WebUtils.toHttp(servletRequest);
        TokenValue tokenValue = null;
        try {
            tokenValue = DefaultTokenService.TOKEN.verifyToken(jwtToken.getToken());
        } catch (Exception e) {
           log.info(e.toString());
            throw new RuntimeException();
        }

        try{
            request.setAttribute("userId", tokenValue.getRid());
            request.setAttribute("per", tokenValue.getPer());
            request.setAttribute("openId", tokenValue.getOid());
            request.setAttribute("phone",tokenValue.getPhoneNum());
            //Long permission = Login.permission();
        }catch (Exception e){
            e.printStackTrace();
        }


        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(authcToken,1, "jwtRealm");

        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取Token
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        Claims claims = jwtUtil.parseJWT(String.valueOf(primaryPrincipal).replace(":null",""));
        SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();
        simpleAuthenticationInfo.addRoles((List<String>)claims.get("per"));
        //System.out.println("鉴权开始==========================");
        return simpleAuthenticationInfo;
    }

}
